package cn.wenhe9.common.exception;

import cn.wenhe9.common.utils.ResultResponse;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author DuJinliang
 * 2022/4/14
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public ResultResponse handlerNotValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{}，异常类型：{}", e.getMessage(), e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach(item -> {
            String message = item.getDefaultMessage();
            String filed = item.getField();
            map.put(filed, message);
        });
        return ResultResponse.build(400, "数据校验出现问题").data(map);
    }

    @ExceptionHandler(Throwable.class)
    public ResultResponse handlerException(Throwable e){
        log.error("出现异常{}，异常类型：{}", e.getMessage(), e.getCause());
        return ResultResponse.fail();
    }
}
